package com.example.aftersales.controller;

import com.example.aftersale.dto.ApiResponse;
import com.example.aftersale.dto.LoginRequest;
import com.example.aftersale.dto.LoginResponse;
import com.example.aftersale.entity.User;
import com.example.aftersale.service.UserService;
import com.example.aftersale.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@RequestBody LoginRequest loginRequest) {
        User user = userService.findByUsername(loginRequest.getUsername());

        if (user == null || !user.getPassword().equals(loginRequest.getPassword())) { // 密码未加密，仅演示
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("账号或密码错误！"));
        }

        if (!user.getRole().name().equalsIgnoreCase(loginRequest.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error("角色不匹配！"));
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getUsername(), user.getRole().name());

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUsername(user.getUsername());
        loginResponse.setRole(user.getRole().name());
        loginResponse.setToken(token);

        return ResponseEntity.ok(ApiResponse.success(loginResponse, "登录成功！"));
    }

    // TODO: 注册功能，实际应该有独立的注册接口
}
